using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Pixysoft
{
    public class StreamCoder
    {
        private static StreamCoder instance;
        public static StreamCoder Instance
        {
            get
            {
                lock (typeof(StreamCoder))
                {
                    if (instance == null)
                        instance = new StreamCoder();
                    return instance;
                }
            }
        }

        public Stream ToStream(byte[] value)
        {
            return new MemoryStream(value);
        }

        public Stream ToStream(string value)
        {
            return ToStream(StringCoder.StringToByte(value));
        }

        public byte[] ToBytes(Stream value)
        {
            List<byte> lineBuf = new List<byte>();

            byte[] buffer = new byte[1024];

            while (true)
            {
                int offset = value.Read(buffer, 0, 1024);

                if (offset <= 0)
                    break;

                for (int i = 0; i < offset; i++)
                {
                    lineBuf.Add(buffer[i]);
                }
            }


            if (lineBuf.Count > 0)
            {
                return lineBuf.ToArray();
            }

            return null;
        }

        private void test()
        {
            string hello = "fuck";

            Stream stream = ToStream(hello);

            byte[] value = ToBytes(stream);

            Console.Write(Pixysoft.StringCoder.ByteToString(value));
        }
    }
}
